package edu.zjut.hjg.saas.kwmp.web.controller.teacher;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.PAGE_SIZE;
import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import edu.zjut.hjg.saas.biz.model.Activity;
import edu.zjut.hjg.saas.biz.model.Album;
import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.service.ActivityService;
import edu.zjut.hjg.saas.biz.service.AlbumService;
import edu.zjut.hjg.saas.biz.support.AlbumType;
import edu.zjut.hjg.saas.biz.support.Paginated;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.common.annotation.RequestAttribute;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

@Controller
@RequestMapping("/teacher/activity")
public class ActivityManageController {
    private static final Log log = LogFactory.getLog(ActivityManageController.class);

    @Autowired
    private ActivityService  activityService;

    @Autowired
    private AlbumService     albumService;

    @RequestMapping("/picture/upload.htm")
    public void uploadPicture(@RequestAttribute Kindergarten app, Model model) {
        model.addAttribute("albums", albumService.listAllByAlbumTypeAndAppId(AlbumType.ACTIVITY,
                app.getId()));
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "/picture/doUpload.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doUploadPicture(@RequestAttribute Kindergarten app,
                                               UserSession session,
                                               @RequestParam("file") MultipartFile file,
                                               Integer albumId, String brief)
            throws IllegalStateException, IOException {
        Activity activity = new Activity();
        activity.setKindergarten(app);
        activity.getAlbum().setId(albumId);
        activity.getUser().setId(session.getId());
        activity.setBrief(brief);
        File targetFile = activityService.create(activity, file.getOriginalFilename(), session
                .getLoginId());
        file.transferTo(targetFile);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        return map;
    }

    @RequestMapping("/picture/list.htm")
    public void listPictures(
                             @RequestAttribute Kindergarten app,
                             @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                             @RequestParam("albumId") int albumId, Model model) {
        if (page < 1) {
            page = 1;
        }
        Integer appId = app.getId();
        model.addAttribute("album", albumService.findByIdAndAppId(albumId, appId));
        model.addAttribute("paginated", activityService.listByAlbumIdAndAppId(albumId, appId,
                PAGE_SIZE, page));
    }

    @RequestMapping("/picture/detail.htm")
    public void showPicture(@RequestAttribute Kindergarten app, @RequestParam("id") int id,
                            Model model) {
        model.addAttribute("activity", activityService.findByIdAndAppId(id, app.getId()));
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping("/picture/delete.htm")
    public String deletePicture(@RequestAttribute Kindergarten app, @RequestParam("id") int id,
                                UserSession session, @RequestParam("albumId") int albumId,
                                Model model) {
        activityService.deleteByIdAndAppId(id, app.getId(), session.getLoginId());
        model.addAttribute("albumId", albumId);
        return "redirect:/teacher/activity/picture/list.htm";
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "/album/doCreate.htm", method = RequestMethod.POST)
    public String doCreateAlbum(@RequestAttribute Kindergarten app, UserSession session,
                                String name, Model model) {
        Album album = new Album();
        album.setAlbumType(AlbumType.ACTIVITY);
        album.setKindergarten(app);
        album.setName(name);
        albumService.create(album, session.getLoginId());
        model.addAttribute("message", "创建成功");
        return "teacher/activity/album/create";
    }

    @RequestMapping("/album/list.htm")
    public void listAlbums(
                           @RequestAttribute Kindergarten app,
                           @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                           Model model) {
        if (page < 1) {
            page = 1;
        }
        Paginated<Album> paginated = albumService.listByAlbumTypeAndAppId(AlbumType.ACTIVITY, app
                .getId(), PAGE_SIZE, page);
        model.addAttribute("paginated", paginated);
        model.addAttribute("covers", activityService.getAlbumCoversByAlbums(paginated.getValues()));
    }

    @RequestMapping("/album/delete.htm")
    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @ResponseBody
    public Map<String, Object> deleteAlbum(@RequestAttribute Kindergarten app, UserSession session,
                                           @RequestParam("id") int id) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            albumService.deleteByIdAndAppId(id, app.getId(), session.getLoginId());
            result.put("success", true);
        } catch (Exception e) {
            log.error("delete album error: " + e.getMessage(), e);
            result.put("success", false);
        }
        return result;
    }
}
